#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/19 19:49
# @Author  : Tom_zc
# @FileName: filter-event.py
# @Software: PyCharm
import os
import sys
import json
import logging

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


def main():
    payload = os.getenv("WEBHOOK_PAYLOAD")
    if not payload:
        logging.info("Error: WEBHOOK_PAYLOAD must not be empty")
        sys.exit(-1)
    payload_body = json.loads(payload)
    event_type = payload_body.get("event_type")
    if not event_type:
        logging.info("Error:Receive the invalid request: event type: {}".format(event_type))
        sys.exit(-1)
    comment = payload_body['object_attributes']['description']
    action = payload_body['object_attributes'].get("action")
    update_reason = payload_body['object_attributes'].get("update_reason")
    logging.info("-----------------------:{}".format(payload_body))
    logging.info(
        "Receive the request: event type: {},action:{},update reason:{},comment:{}, ".format(event_type, action,
                                                                                             update_reason, comment))
    if event_type.lower() == "merge_request" and action in ["reopen", "open"]:
        sys.exit(0)
    elif event_type.lower() == "note" and comment.strip().lower() == "/retest":
        sys.exit(0)
    elif event_type.lower() == "merge_request" and action == "update" and update_reason == "source update":
        sys.exit(0)
    logging.info("Error: Receive the invalid request")
    sys.exit(-1)


if __name__ == '__main__':
    main()
